package com.dmw.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.dmw.entity.DmOrder;
import com.dmw.service.DmTradeService;
import com.dmw.util.AlipayConfig;
import com.dmw.util.DmOrderOut;
import com.dmw.util.DtoUtil;
import com.dmw.vo.PayVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付处理控制器
 *
 * @author hduser
 */
@RestController
public class AliPaymentController {
//    @Resource
//    private AlipayConfig alipayConfig;

    @Resource
    private DmTradeService dmTradeService;

    @GetMapping("createqccode")
    public Object pay(@RequestParam String orderNo) throws Exception {
        DmOrder order = dmTradeService.loadDmOrderByOrderNo(orderNo);
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        // 调用RSA签名方式
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.GATEWAY_URL,
            AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY,
                AlipayConfig.FORMAT, AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);
        // 封装请求支付信息
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setReturnUrl(AlipayConfig.RETURN_URL);
        request.setNotifyUrl(AlipayConfig.NOTIFY_URL);
//        logger.info("[pay]" + "商户订单编号：" + order.getOrderNo());
//        logger.info("[pay]" + "订单名称：" + order.getItemName());
//        logger.info("[pay]" + "付款金额：" + order.getTotalAmount());

        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(order.getOrderNo()); //设置订单号
        model.setTotalAmount(order.getTotalAmount().toString()); //订单金额
        model.setSubject(order.getItemName()); //订单名称

        request.setBizModel(model);

        HashMap<String, Object> result = new HashMap<String, Object>();

        try {
            //执行请求获取二维码
            AlipayTradePrecreateResponse response = client.execute(request);


            if(response.isSuccess()){

                System.out.println(response.getQrCode());
                System.out.println(response.getCode());
                System.out.println(response.getOutTradeNo());

                //根据订单获取对应的剧集的信息，这里获取的是剧集的编号
                result.put("itemName", order.getItemName());
                result.put("orderNo", order.getOrderNo());
                //获取订单总金额
                result.put("totalAmount", order.getTotalAmount());
                //二维码对应的url
                result.put("codeUrl",response.getQrCode());
            }

        } catch (AlipayApiException e) {
//            throw new BaseException(PayErrorCode.PAY_ALIPAY_ERROR_CODE);
        }

        return DtoUtil.returnDataSuccess(result);
    }

    @GetMapping("alipay")
    public Object pay2(@RequestParam String orderNo) throws Exception {
//        String orderNo= String.valueOf(map.get("orderNo"));
        System.out.println(orderNo);
        DmOrder order = dmTradeService.loadDmOrderByOrderNo(orderNo);
        System.out.println(order);
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        // 调用RSA签名方式
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.GATEWAY_URL,
                AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY,
                AlipayConfig.FORMAT, AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);
        // 封装请求支付信息
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setReturnUrl(AlipayConfig.RETURN_URL);
        request.setNotifyUrl(AlipayConfig.NOTIFY_URL);
//        logger.info("[pay]" + "商户订单编号：" + order.getOrderNo());
//        logger.info("[pay]" + "订单名称：" + order.getItemName());
//        logger.info("[pay]" + "付款金额：" + order.getTotalAmount());

        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(order.getOrderNo()); //设置订单号
        model.setTotalAmount(order.getTotalAmount().toString()); //订单金额
        model.setSubject(order.getItemName()); //订单名称

        request.setBizModel(model);

        DmOrderOut orderResponse = new DmOrderOut();
        HashMap<String, Object> result = new HashMap<String, Object>();
        try {
            //执行请求获取二维码
            AlipayTradePrecreateResponse response = client.execute(request);

            if(response.isSuccess()){
                System.out.println("二维码创建成功");
                result.put("orderNo", order.getOrderNo());
                result.put("itemName", order.getItemName());
                result.put("totalAmount", order.getTotalAmount());
                result.put("qrCode", response.getQrCode());
                System.out.println(result);
            }

        } catch (AlipayApiException e) {
//            throw new BaseException(PayErrorCode.PAY_ALIPAY_ERROR_CODE);
        }

        return result;
    }

    /**
     * 支付宝页面跳转同步通知页面
     */
    @PostMapping("callback")
    public String callback(@RequestBody PayVo vo) throws Exception {
        System.out.println("123567");
        HttpServletRequest request = vo.getRequest();
        HttpServletResponse response = vo.getResponse();

        response.setHeader("Access-Control-Allow-Origin", "*");
        try {
            //获取支付宝GET过来反馈信息
            Map<String, String> params = new HashMap<String, String>();
            request.setCharacterEncoding("UTF-8");
            Map requestParams = request.getParameterMap();
            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
            //商户订单号
            String out_trade_no = request.getParameter("out_trade_no");
            //支付宝交易号
            String trade_no = request.getParameter("trade_no");
            // 交易状态
            String trade_status = request.getParameter("trade_status");
            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
            //计算得出通知验证结果
            //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
//            logger.info("return---------------------------------");
            boolean verify_result = dmTradeService.syncVerifyResult(requestParams);

            if (verify_result) {//验证成功
//                logger.info("[callback]" + "该笔订单支付成功");
//                if(!dmTradeService.processed(out_trade_no, Constants.PayMethod.ZHIFUBAO)){
//                    logger.info("[callback]" + "此笔订单未支付过：" + out_trade_no);
//                    dmTradeService.insertTrade(out_trade_no, trade_no, Constants.PayMethod.ZHIFUBAO);
//                    logger.info("[callback]" + "系统业务处理完成，订单编号为：" + out_trade_no);
//                }
                String id = dmTradeService.loadDmOrderByOrderNo(out_trade_no).getId().toString();
                //提示支付成功
                //response.sendRedirect(String.format(alipayConfig.getPaymentSuccessUrl(), out_trade_no, id));
                return "success"; // 请不要修改或删除
            } else {
                //提示支付失败
//                logger.info("[callback]" + "支付失败，订单编号：" + out_trade_no);
                //response.sendRedirect(alipayConfig.getPaymentFailureUrl());
                return "fail";
            }
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
//            logger.error(e.getMessage());
            return "fail";
        }
    }

}
